import Vue from 'vue';
import Vuex from 'vuex';

import {
	TOKEN_KEY
} from '@/enums/cacheEnum';
import {
	login
} from '@/services/api/auth';
import {
	clearCache,
	getCache,
	removeCache,
	setCache
} from '@/utils/catch';
import {
	socketClient
} from '@/utils/socket1';
import {
	VUE_APP_WS_URL
} from '../../utils/http/url.js'

Vue.use(Vuex);

export default new Vuex.Store({
	state: {
		token: null,
		deviceInfo: null,
		socket: null,
		websocketId: null,
	},
	getters: {
		getToken: (state) => {
			return state.token;
		},
		isLogin: (state) => {
			return !!state.token;
		},
	},
	mutations: {
		SET_TOKEN(state, token) {
			state.token = token;
		},
		SET_DEVICE_INFO(state, deviceInfo) {
			state.deviceInfo = deviceInfo;
		},
		SET_WEBSOCKET_ID(state, websocketId) {
			state.websocketId = websocketId;
		},
		SET_SOCKET(state, socket) {
			state.socket = socket;
		}
	},
	actions: {
		initToken({
			commit
		}) {
			const token = getCache(TOKEN_KEY) || null;
			commit('SET_TOKEN', token);
		},
		setToken({
			commit
		}, token) {
			setCache(TOKEN_KEY, token);
			commit('SET_TOKEN', token);
		},
		setDeviceInfo({
			commit
		}, deviceInfo) {
			commit('SET_DEVICE_INFO', deviceInfo);
		},
		setWebsocketId({
			commit
		}, websocketId) {
			commit('SET_WEBSOCKET_ID', websocketId);
		},
		initSocket({
			commit,
			state
		}, status = false) {
			const wsUrl = VUE_APP_WS_URL + state.websocketId;
			if (!state.socket) {
				const socket = new socketClient(wsUrl);
				socket.initWebSocket(status);
				commit('SET_SOCKET', socket);
			}
		},

		checkSocket({
			dispatch,
			state
		}, wsUUID) {
			console.log('重连检测 socket是不是一致');
			if (!state.socket || !state.socket.websocket || wsUUID !== state.socket.wsUUID) {
				console.log('重连检测 socket不一致');
				dispatch('initSocket');
			}
			uni.$emit('checkSocket');
		},
		async login({
			commit
		}, params) {
			try {
				const data = await login(params);
				commit('SET_TOKEN', data.token);
				return Promise.resolve(data);
			} catch (err) {
				return Promise.reject(err);
			}
		},
		async loginOut({
			commit
		}) {
			try {
				removeCache(TOKEN_KEY);
				clearCache();
				commit('SET_TOKEN', null);
				return Promise.resolve();
			} catch (err) {
				return Promise.reject(err);
			}
		}
	},
});